package com.feng.filter;

import com.feng.common.RestBean;
import com.feng.common.RestCode;
import com.feng.utils.IPUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.xiaoleilu.hutool.json.JSONUtil;
import io.micrometer.core.instrument.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class IpFilter extends ZuulFilter {

    // IP黑名单列表
//    private List<String> blackIpList = Arrays.asList("127.0.0.1");
    private List<String> blackIpList = Arrays.asList("127.0.0.1","192.168.2.102");

    public IpFilter() {
        super();
    }

    @Override
    public boolean shouldFilter() {
        // 进行跨域请求的时候，并且请求头中有额外参数，比如token，客户端会先发送一个OPTIONS请求来探测后续需要发起的跨域POST请求是否安全可接受
        // 所以这个请求就不需要拦截，下面是处理方式
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            log.info("OPTIONS请求不做拦截操作");
            return false;
        }
        return true;
//        return true;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        final HttpServletRequest request = ctx.getRequest();
        String ip = IPUtils.getIpAddr(request);

        // 记录下请求内容
        log.info("send {} request to {} from {} ",
            request.getMethod(), request.getRequestURL().toString(), request.getRemoteAddr());

        // 在黑名单中禁用
        if (StringUtils.isNotBlank(ip) && blackIpList.contains(ip)) {
            ctx.setSendZuulResponse(false);
            ctx.set("sendForwardFilter.ran", true);
//            ctx.setResponseStatusCode(401);
            RestBean data = RestBean.error(RestCode.ROLE_ERROR,"非法请求 ");
            ctx.setResponseBody(JSONUtil.toJsonStr(data));
            ctx.getResponse().setContentType("application/json; charset=utf-8");
            return null;
        }
        return null;
    }
}